package com.hxy.hrm.feign.config;

import com.hxy.hrm.util.HttpUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
public class OAuth2FeignRequestInterceptor implements RequestInterceptor {
    private static String TEMPTOKENURL = "http://localhost:4020/oauth/token?client_id=%s&client_secret=%s&grant_type=client_credentials";
    //请求头中的token
    private final String AUTHORIZATION_HEADER = "Authorization";
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //获取ServletRequest属性
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        //从requestAttributes获取请求对象
        HttpServletRequest request = requestAttributes.getRequest();

        //从请求对象中就可以获取token请求头
        String token = request.getHeader(AUTHORIZATION_HEADER);
        if (StringUtils.isEmpty(token)){
            String url = String.format(TEMPTOKENURL, "temp", "1");
            Map<String, Object> map = HttpUtil.sendPost(url);
            token = (String) map.get("access_token");
            requestTemplate.header(AUTHORIZATION_HEADER,"Bearer "+token);
        }
    }
}